import { reactive, computed, ref } from "vue";
import { message } from "@/utils/message";
import { analyzeIps, getTaskTemplateList } from "@/api/task";
import type { FormItemConfig } from "@/components/DynamicForm/types";

let isTransformed = false;

export function useTaskForm() {
  // 表单数据
  const searchFormData = reactive({
    search: "",
  });

  const addTaskFormData = reactive({
    name: "",
    target: "",
    ignore: "",
    template: "",
    scheduledTasks: false, // 定时任务开关
    cycleType: "", // 监控周期类型
    hour: 0, // 小时
    minute: 0, // 分钟
    day: 1, // 天数或日期
    week: 0, // 星期几
    deduplicate: false, // 去重
    subdomainDeduplicate: false, // 子域名去重
    // scanTemplate: "", // 扫描模板
    isTransformed: false, // 是否已转换（用于互联网探测验证）
  });

  // 转换加载状态
  const transformLoading = reactive({
    isLoading: false,
  });

  // 扫描类型列表
  const templateList = ref<any[]>([]);

  // 星期选项
  const weekOptions = [
    { label: "星期日", value: 0 },
    { label: "星期一", value: 1 },
    { label: "星期二", value: 2 },
    { label: "星期三", value: 3 },
    { label: "星期四", value: 4 },
    { label: "星期五", value: 5 },
    { label: "星期六", value: 6 },
  ];

  // 获取扫描类型列表
  const getTemplateList = async () => {
    try {
      const { data } = await getTaskTemplateList({
        search: "",
        pageIndex: 1,
        pageSize: 1000,
      });
      if (data && data.list) {
        templateList.value = data.list.map((item: any) => ({
          label: item.name,
          value: item.id,
        }));
      }
    } catch (err) {
      console.error("获取扫描类型列表失败:", err);
    }
  };

  // 转换互联网探测目标
  const transformInternetTargets = async (
    targetFormData: any = addTaskFormData
  ) => {
    isTransformed = false;
    if (targetFormData.template !== "684db9a5b02f85e29536da04") {
      message("只有互联网探测类型才能进行转换", { type: "warning" });
      return;
    }

    if (!targetFormData.target.trim()) {
      message("请先输入扫描目标", { type: "warning" });
      return;
    }

    transformLoading.isLoading = true;
    try {
      // 解析输入的目标内容
      const inputTargets = targetFormData.target
        .split(/[\n,]/)
        .map((item: string) => item.trim())
        .filter(Boolean);

      if (inputTargets.length === 0) {
        message("请输入有效的扫描目标", { type: "warning" });
        return;
      }

      // 调用API进行目标解析
      const response: any = await analyzeIps({
        assets: targetFormData.target,
      });

      if (response?.ips) {
        targetFormData.target = response.ips.join("\n");
        // targetFormData.isTransformed = true;
        isTransformed = true;
      }
      // if (response && response.data) {
      //   // 处理API返回的数据
      //   let transformedTargets = [];

      //   if (response.data.ips && Array.isArray(response.data.ips)) {

      //   } else if (response.data.list && Array.isArray(response.data.list)) {
      //     transformedTargets = response.data.list
      //       .map(
      //         (item: any) => item.ip || item.target || item.host || item.asset
      //       )
      //       .filter(Boolean);
      //   } else {
      //     // 如果API没有返回预期格式，使用原始输入
      //     transformedTargets = inputTargets;
      //   }

      //   // 将转换后的结果回显到输入框
      //   targetFormData.target = transformedTargets.join("\n");
      //   targetFormData.isTransformed = true;

      //   message(`转换成功，处理了 ${transformedTargets.length} 个目标`, {
      //     type: "success",
      //   });
      // } else {
      //   message("转换失败，API返回数据格式错误", { type: "error" });
      // }
    } catch (error) {
      console.error("转换失败:", error);
      message("转换失败，请重试", { type: "error" });
    } finally {
      transformLoading.isLoading = false;
    }
  };

  // 搜索表单配置
  const searchFormConfig: FormItemConfig[] = [
    {
      key: "search",
      name: "任务名称",
      type: "input",
      placeholder: "任务名称",
      params: {
        maxLength: 30,
        clearable: true,
      },
      col: { xs: 24, sm: 12, md: 8, lg: 6 },
    },
    // {
    //   key: "creater",
    //   name: "创建人",
    //   type: "input",
    //   placeholder: "创建人",
    //   params: {
    //     maxLength: 30,
    //     clearable: true
    //   },
    //   col: { xs: 24, sm: 12, md: 8, lg: 6 }
    // },
    // {
    //   key: "ipscope",
    //   name: "目标",
    //   type: "input",
    //   placeholder: "目标",
    //   params: {
    //     maxLength: 30,
    //     clearable: true
    //   },
    //   col: { xs: 24, sm: 12, md: 8, lg: 6 }
    // }
  ];

  // 新建任务表单配置（包含扫描类型节点2）
  const getAddTaskFormConfig = (
    formData: any = addTaskFormData,
    remoteTemplateList: any[] = []
  ): FormItemConfig[] => {
    return [
      {
        key: "name",
        name: "任务名称",
        type: "input",
        required: true,
        placeholder: "请输入任务名称",
        params: {
          maxLength: 50,
          clearable: true,
        },
      },
      {
        key: "target",
        name: "扫描目标",
        type: "textarea",
        required: true,
        placeholder:
          "请输入扫描目标，如：192.168.1.1-254、www.baidu.com，多个目标用换行或逗号分隔",
        params: {
          rows: 4,
          clearable: true,
        },
      },
      // 添加转换按钮 - 只在互联网探测时显示
      {
        key: "transformButton",
        name: "转换",
        type: "button",
        show: (formData) => formData.template === "684db9a5b02f85e29536da04",
        params: {
          text: "转换目标",
          type: "primary",
          loading: transformLoading.isLoading,
          onClick: () => transformInternetTargets(formData),
        },
      },
      {
        key: "ignore",
        name: "忽略目标",
        type: "textarea",
        placeholder: "请输入需要忽略的目标，多个目标用换行或逗号分隔",
        params: {
          rows: 3,
          clearable: true,
        },
      },
      {
        key: "template",
        name: "扫描类型",
        type: "select",
        required: true,
        placeholder: "请选择扫描类型",
        options: templateList.value,
        params: {
          clearable: true,
        },
      },
      {
        key: "template2",
        name: "扫描类型节点2",
        type: "select",
        required: true,
        placeholder: "请选择扫描类型节点2",
        options: remoteTemplateList,
        params: {
          clearable: true,
        },
        col: {
          span: 24,
        },
        show: (formData) => !formData.id, // 只有在新建任务时显示，查看任务时隐藏
      },
      {
        key: "scheduledTasks",
        name: "定时任务",
        type: "switch",
      },
      {
        key: "cycleType",
        name: "监控周期",
        type: "select",
        show: (formData) => formData.scheduledTasks,
        required: true,
        placeholder: "请选择监控周期",
        options: [
          { label: "每天", value: "daily" },
          { label: "N天", value: "ndays" },
          { label: "N小时", value: "nhours" },
          { label: "每星期", value: "weekly" },
          { label: "每月", value: "monthly" },
        ],
        params: {
          clearable: true,
        },
      },
      // daily: hour + minute
      {
        key: "hour",
        name: "小时",
        type: "number",
        show: (formData) =>
          formData.scheduledTasks &&
          (formData.cycleType === "daily" ||
            formData.cycleType === "ndays" ||
            formData.cycleType === "weekly" ||
            formData.cycleType === "monthly"),
        required: true,
        defaultValue: 0,
        params: {
          min: 0,
          max: 23,
          step: 1,
        },
      },
      {
        key: "minute",
        name: "分钟",
        type: "number",
        show: (formData) => formData.scheduledTasks && formData.cycleType,
        required: true,
        defaultValue: 0,
        params: {
          min: 0,
          max: 59,
          step: 1,
        },
      },
      // ndays: day + hour + minute
      {
        key: "day",
        name: "间隔天数",
        type: "number",
        show: (formData) =>
          formData.scheduledTasks && formData.cycleType === "ndays",
        required: true,
        defaultValue: 1,
        params: {
          min: 1,
          max: 365,
          step: 1,
        },
      },
      // nhours: hour + minute (hour 表示间隔小时数)
      {
        key: "hour",
        name: "间隔小时数",
        type: "number",
        show: (formData) =>
          formData.scheduledTasks && formData.cycleType === "nhours",
        required: true,
        defaultValue: 1,
        params: {
          min: 1,
          max: 168, // 一周的小时数
          step: 1,
        },
      },
      // weekly: week + hour + minute
      {
        key: "week",
        name: "星期几",
        type: "select",
        show: (formData) =>
          formData.scheduledTasks && formData.cycleType === "weekly",
        required: true,
        placeholder: "请选择星期几",
        options: weekOptions,
        params: {
          clearable: true,
        },
      },
      // monthly: day + hour + minute
      {
        key: "day",
        name: "日期",
        type: "number",
        show: (formData) =>
          formData.scheduledTasks && formData.cycleType === "monthly",
        required: true,
        defaultValue: 1,
        params: {
          min: 1,
          max: 31,
          step: 1,
        },
      },
    ];
  };

  // 表单验证逻辑
  const validateTaskForm = (formData: any = addTaskFormData) => {
    if (!formData.name.trim()) {
      message("请输入任务名称", { type: "error" });
      return false;
    }

    if (!formData.target.trim()) {
      message("请输入扫描目标", { type: "error" });
      return false;
    }

    if (!formData.template) {
      message("请选择扫描类型", { type: "error" });
      return false;
    }

    // 互联网探测类型必须进行转换
    if (formData.template === "684db9a5b02f85e29536da04" && !isTransformed) {
      message("互联网探测类型必须先转换目标才能提交", { type: "error" });
      return false;
    }

    // if (!formData.scanTemplate) {
    //   message("请选择扫描模板", { type: "error" });
    //   return false;
    // }

    // 定时任务开启时的验证
    if (formData.scheduledTasks) {
      if (!formData.cycleType) {
        message("请选择监控周期", { type: "error" });
        return false;
      }

      // 验证分钟字段
      if (formData.minute < 0 || formData.minute > 59) {
        message("请设置正确的分钟数(0-59)", { type: "error" });
        return false;
      }

      // 根据不同的周期类型进行相应验证
      switch (formData.cycleType) {
        case "daily":
          if (formData.hour < 0 || formData.hour > 23) {
            message("请设置正确的小时数(0-23)", { type: "error" });
            return false;
          }
          break;

        case "ndays":
          if (!formData.day || formData.day < 1) {
            message("请设置正确的间隔天数", { type: "error" });
            return false;
          }
          if (formData.hour < 0 || formData.hour > 23) {
            message("请设置正确的小时数(0-23)", { type: "error" });
            return false;
          }
          break;

        case "nhours":
          if (!formData.hour || formData.hour < 1) {
            message("请设置正确的间隔小时数", { type: "error" });
            return false;
          }
          break;

        case "weekly":
          if (formData.week < 0 || formData.week > 6) {
            message("请选择正确的星期", { type: "error" });
            return false;
          }
          if (formData.hour < 0 || formData.hour > 23) {
            message("请设置正确的小时数(0-23)", { type: "error" });
            return false;
          }
          break;

        case "monthly":
          if (!formData.day || formData.day < 1 || formData.day > 31) {
            message("请设置正确的日期(1-31)", { type: "error" });
            return false;
          }
          if (formData.hour < 0 || formData.hour > 23) {
            message("请设置正确的小时数(0-23)", { type: "error" });
            return false;
          }
          break;
      }
    }

    return true;
  };

  // 重置表单
  const resetAddTaskForm = () => {
    Object.assign(addTaskFormData, {
      name: "",
      target: "",
      ignore: "",
      template: "",
      scheduledTasks: false,
      cycleType: "",
      hour: 0,
      minute: 0,
      day: 1,
      week: 0,
      deduplicate: false,
      subdomainDeduplicate: false,
      // scanTemplate: "",
      isTransformed: false,
    });
  };

  // 获取搜索参数
  const getSearchParams = () => {
    return searchFormData.search;
  };

  // 查看任务表单配置（不包含扫描类型节点2）
  const getViewTaskFormConfig = (
    formData: any = addTaskFormData,
    remoteTemplateList: any[] = []
  ): FormItemConfig[] => {
    return [
      {
        key: "name",
        name: "任务名称",
        type: "input",
        required: true,
        placeholder: "请输入任务名称",
        params: {
          maxLength: 50,
          clearable: true,
        },
      },
      {
        key: "target",
        name: "扫描目标",
        type: "textarea",
        required: true,
        placeholder:
          "请输入扫描目标，如：192.168.1.1-254、www.baidu.com，多个目标用换行或逗号分隔",
        params: {
          rows: 4,
          clearable: true,
        },
      },
      // 添加转换按钮 - 只在互联网探测时显示
      {
        key: "transformButton",
        name: "转换",
        type: "button",
        show: (formData) => formData.template === "684db9a5b02f85e29536da04",
        params: {
          text: "转换目标",
          type: "primary",
          loading: transformLoading.isLoading,
          onClick: () => transformInternetTargets(formData),
        },
      },
      {
        key: "ignore",
        name: "忽略目标",
        type: "textarea",
        placeholder: "请输入需要忽略的目标，多个目标用换行或逗号分隔",
        params: {
          rows: 3,
          clearable: true,
        },
      },
      {
        key: "template",
        name: "扫描类型",
        type: "select",
        required: true,
        placeholder: "请选择扫描类型",
        options: templateList.value,
        params: {
          clearable: true,
        },
      },
      // 注意：这里不包含 template2 字段
      {
        key: "scheduledTasks",
        name: "定时任务",
        type: "switch",
      },
      {
        key: "cycleType",
        name: "监控周期",
        type: "select",
        show: (formData) => formData.scheduledTasks,
        required: true,
        placeholder: "请选择监控周期",
        options: [
          { label: "每天", value: "daily" },
          { label: "N天", value: "ndays" },
          { label: "N小时", value: "nhours" },
          { label: "每星期", value: "weekly" },
          { label: "每月", value: "monthly" },
        ],
        params: {
          clearable: true,
        },
      },
      // daily: hour + minute
      {
        key: "hour",
        name: "小时",
        type: "number",
        show: (formData) =>
          formData.scheduledTasks &&
          (formData.cycleType === "daily" ||
            formData.cycleType === "ndays" ||
            formData.cycleType === "weekly" ||
            formData.cycleType === "monthly"),
        required: true,
        defaultValue: 0,
        params: {
          min: 0,
          max: 23,
          step: 1,
        },
      },
      {
        key: "minute",
        name: "分钟",
        type: "number",
        show: (formData) => formData.scheduledTasks && formData.cycleType,
        required: true,
        defaultValue: 0,
        params: {
          min: 0,
          max: 59,
          step: 1,
        },
      },
      // ndays: day + hour + minute
      {
        key: "day",
        name: "间隔天数",
        type: "number",
        show: (formData) =>
          formData.scheduledTasks && formData.cycleType === "ndays",
        required: true,
        defaultValue: 1,
        params: {
          min: 1,
          max: 365,
          step: 1,
        },
      },
      // nhours: hour + minute (hour 表示间隔小时数)
      {
        key: "hour",
        name: "间隔小时数",
        type: "number",
        show: (formData) =>
          formData.scheduledTasks && formData.cycleType === "nhours",
        required: true,
        defaultValue: 1,
        params: {
          min: 1,
          max: 168, // 一周的小时数
          step: 1,
        },
      },
      // weekly: week + hour + minute
      {
        key: "week",
        name: "星期几",
        type: "select",
        show: (formData) =>
          formData.scheduledTasks && formData.cycleType === "weekly",
        required: true,
        placeholder: "请选择星期几",
        options: weekOptions,
        params: {
          clearable: true,
        },
      },
      // monthly: day + hour + minute
      {
        key: "day",
        name: "日期",
        type: "number",
        show: (formData) =>
          formData.scheduledTasks && formData.cycleType === "monthly",
        required: true,
        defaultValue: 1,
        params: {
          min: 1,
          max: 31,
          step: 1,
        },
      },
    ];
  };

  return {
    // 数据
    searchFormData,
    addTaskFormData,
    weekOptions,
    transformLoading,
    templateList,

    // 配置
    searchFormConfig,
    getAddTaskFormConfig,
    getViewTaskFormConfig,

    // 方法
    validateTaskForm,
    resetAddTaskForm,
    getSearchParams,
    transformInternetTargets,
    getTemplateList,
    // processTargets,
  };
}
